import configparser
import datetime
import logging
import os
import time
import pysftp
import shutil

from redis import Redis

from utils.bloader import UpLoaderPlus
from utils.message import MessagefromJson

"""
    读取配置
"""
cf = configparser.ConfigParser()
cf.read("./db.conf")

redis_host = cf.get("redis", "host")
redis_password = cf.get("redis", "password")
queue = cf.get("redis", "queue")

sftp_host = cf.get("sftp", "host")
sftp_user = cf.get("sftp", "user")
sftp_pass = cf.get("sftp", "passwd")


if not (cf.has_option("cookie", "passwd") and cf.has_option("cookie", "user")):
    raise FileExistsError("请在db.conf中修改添加正确的cookie配置")

uper = UpLoaderPlus(username=cf.get("cookie", "user"), passwd=cf.get("cookie", "passwd"))

"""
    创建日志对象
"""
logger = logging.getLogger("waitLive")
logger.setLevel(level=logging.DEBUG)

formatter = logging.Formatter(
    fmt="%(asctime)s %(name)s %(filename)s %(message)s",
    datefmt="%Y/%m/%d %X"
)

ch = logging.StreamHandler()
ch.setFormatter(formatter)
logger.addHandler(ch)

"""
    设置sftp参数
"""

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None

with Redis(host=redis_host, password=redis_password) as redis_conn:
    while True:
        logger.info("work lop")
        json_str = redis_conn.brpop(queue, timeout=0)
        logger.info(f"{json_str}处理开始")

        videoInfo = MessagefromJson(json_str)

        """
            下载视频图片和文件
        """
        dt = datetime.datetime.now()

        v_name = "video.mp4"
        g_name = "graph.jpg"
        v_tmp = f"./{v_name}"
        g_tmp = f"./{g_name}"

        ts = f"{dt.year}{dt.month:02}{dt.day:02}{dt.hour:02}{dt.minute:02}{dt.second:02}"
        dir_path = os.path.join(os.path.abspath('task'), ts)

        v_dst_path = os.path.join(dir_path, v_name)
        g_dst_path = os.path.join(dir_path, g_name)

        with pysftp.Connection(sftp_host, port=22, username=sftp_user, password=sftp_pass,
                               cnopts=cnopts) as sftp:

            sftp.get(videoInfo.video_url, preserve_mtime=True)
            sftp.get(videoInfo.graph_path, preserve_mtime=True)

            if os.path.exists(v_tmp) and os.path.exists(g_tmp):

                shutil.move(v_tmp, v_dst_path)
                shutil.move(g_tmp, g_dst_path)

            else:
                logger.fatal("文件不全，跳过此任务!")
                if os.path.exists(v_tmp):
                    os.remove(v_tmp)
                if os.path.exists(g_tmp):
                    os.remove(g_tmp)
                continue
        """
            上传阿b
        """

        uper.upVideo(v_dst_path, videoInfo.video_title, videoInfo.channel, videoInfo.tag_str, videoInfo.video_desc, videoInfo.video_url, g_dst_path, videoInfo.dynamic_str)




        logger.info(f"{json_str}处理结束")
